package com.wenxin.demo.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class WecomUtil {

    private OkHttpClient client;

    @Value("${wecom.corp-id}")
    private String corpId;

    @Value("${wecom.corpsecret}")
    private String corpsecret;

    @PostConstruct
    public void init() {
        client = new OkHttpClient().newBuilder().build();
    }

    @Resource
    RedisTemplate<String, Object> redisTemplate;

    public String getAccessToken() throws IOException {
        if (redisTemplate.hasKey("access_token_wecom")) {
            return (String) redisTemplate.opsForValue().get("access_token_wecom");
        } else {
            String accessToken = null;
            Request request = new Request.Builder()
                    .url("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpId + "&corpsecret=" + corpsecret)
                    .method("GET", null)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                JSONObject json = JSON.parseObject(response.body().string());
                accessToken = json.getString("access_token");
            }
            if (null != accessToken && !"".equals(accessToken)) {
                redisTemplate.opsForValue().set("access_token_wecom", accessToken, 3600, TimeUnit.SECONDS);
            }
            return accessToken;
        }
    }

    public void sendMsg(String toUser, String msg) throws IOException {
        String accessToken = getAccessToken();
        Map<String, Object> param = new HashMap<>();
        param.put("touser", toUser);
        param.put("msgtype", "text");
        param.put("agentid", "1000002");
        Map<String, String> text = new HashMap<>();
        text.put("content", msg);
        param.put("text", text);
        String jsonString = JSON.toJSONString(param);

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonString);
        Request request = new Request.Builder()
                .url("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            System.out.println(response.body().string());
        } else {
            System.out.println("error");
        }
    }
}
